﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using NeoModulusBusinessRulesDLLBuilder.Classes;
using NeoModulusBusinessRulesDLLBuilder.Dialogs;

namespace NeoModulusBusinessRulesDLLBuilder.UserControls
{
    public partial class usrObjectTree : UserControl
    {
        private AddNewObjectWizard _addNewObjectWizard;
        private string _projectName = string.Empty;

        public const string SAVELOCATION = "SaveLocation";
        public List<ObjectDefinition> CurrentObjects;


        public delegate void ObjectSelected(ObjectDefinition inObject);
        public event ObjectSelected OnObjectSelected;

        public usrObjectTree()
        {
            InitializeComponent();
        }

        public void OpenProject(string inProjetName)
        {
            ClearProject();

            if (SAVELOCATION[(SAVELOCATION.Length - 1)] == '\\')
            {
                if (!Directory.Exists(ConfigurationManager.AppSettings[SAVELOCATION] + inProjetName))
                {
                    Directory.CreateDirectory(ConfigurationManager.AppSettings[SAVELOCATION] + inProjetName);
                }
                else
                {
                    LoadProject(ConfigurationManager.AppSettings[SAVELOCATION] + inProjetName);
                }
            }
            else
            {
                if (!Directory.Exists(ConfigurationManager.AppSettings[SAVELOCATION] + @"\" + inProjetName))
                {
                    Directory.CreateDirectory(ConfigurationManager.AppSettings[SAVELOCATION] + @"\" + inProjetName);
                }
                else
                {
                    LoadProject(ConfigurationManager.AppSettings[SAVELOCATION] + @"\" + inProjetName); 
                }
            }

            _projectName = inProjetName;
        }

        private void LoadProject(string inProjetName)
        {
            foreach (string file in Directory.EnumerateFiles(inProjetName))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ObjectDefinition));

                ObjectDefinition od = (ObjectDefinition) serializer.Deserialize(new FileStream(file, FileMode.Open));

                AddToObjectTree(od);
            }
        }


        public void SaveProject()
        {

            if (CurrentObjects != null && !string.IsNullOrEmpty(_projectName))
            {
                foreach (ObjectDefinition od in CurrentObjects)
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(ObjectDefinition));

                    if (SAVELOCATION[(SAVELOCATION.Length - 1)] == '\\')
                    {
                        TextWriter textWriter = new StreamWriter(ConfigurationManager.AppSettings[SAVELOCATION] + _projectName + @"\" + od.ObjectName);
                        serializer.Serialize(textWriter, od);
                        textWriter.Close();
                    }
                    else
                    {
                        TextWriter textWriter = new StreamWriter(ConfigurationManager.AppSettings[SAVELOCATION] + @"\" + _projectName + @"\" + od.ObjectName);
                        serializer.Serialize(textWriter, od);
                        textWriter.Close();
                    }
                }
            }
        }

        private void ClearProject()
        {
            SaveProject();

            tvObjects.Nodes.Clear();

            CurrentObjects = new List<ObjectDefinition>();
        }

        private void tbObjectTree_ButtonClick(object sender, ToolBarButtonClickEventArgs e)
        {
            if(e.Button == tbbAdd)
            {
                _addNewObjectWizard = new AddNewObjectWizard();
                _addNewObjectWizard.ObjectTree = this;
                _addNewObjectWizard.Closed += new EventHandler(addNewObjectWizard_Closed);
                _addNewObjectWizard.ShowDialog();

            }
            else if(e.Button== tbbDelete)
            {
                
            }
        }

        void addNewObjectWizard_Closed(object sender, EventArgs e)
        {
            if (_addNewObjectWizard.DialogResult == DialogResult.Yes)
            {
                ObjectDefinition od = new ObjectDefinition() { ObjectName = _addNewObjectWizard.NewObjectName};
                AddToObjectTree(od);
            }
        }

        private void AddToObjectTree(ObjectDefinition inObjectDefinition)
        {
            CurrentObjects.Add(inObjectDefinition);
            tvObjects.Nodes.Add(new TreeNode(inObjectDefinition.ObjectName) { Tag = inObjectDefinition });
            SaveProject();
        }

        public bool DoesNameExist(string inObjectName)
        {
            bool oExists = false;

            if (tvObjects.Nodes.Cast<TreeNode>().Any(treeNode => string.Compare(((ObjectDefinition) treeNode.Tag).ObjectName, inObjectName, true) == 0))
            {
                oExists = true;
                return oExists;
            }

            return oExists;
        }

        private void tvObjects_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (OnObjectSelected != null && e.Node.Tag is ObjectDefinition)
            {
                ObjectDefinition od = (ObjectDefinition) e.Node.Tag;
                OnObjectSelected(od);
            }
        }
    }
}
